package com.example.admin.brainwave.utils;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;


import java.io.IOException;

public class AudioUtils {


    private static MediaPlayer mPlayer;
    private static boolean isPause = false;

    public static void playSound(Context context, int resId, MediaPlayer.OnCompletionListener listener) {
        if (mPlayer == null) {
            mPlayer = new MediaPlayer();
        } else {
            mPlayer.reset();
        }
        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mPlayer.setOnCompletionListener(listener);
        mPlayer.setOnErrorListener((mp, what, extra) -> {
            mPlayer.reset();
            return false;
        });
        try {
            mPlayer.setDataSource(context, Uri.parse(getAudioPath(context, resId)));
            mPlayer.prepare();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            throw new RuntimeException("读取文件异常：" + e.getMessage());
        }
        mPlayer.start();
        isPause = false;
    }


    private static String getAudioPath(Context context, int resId) {
        return "android.resource://" + context.getPackageName() + "/" + resId;
    }

    public static void pause() {
        if (mPlayer != null && mPlayer.isPlaying()) {
            mPlayer.pause();
            isPause = true;
        }
    }

    // 继续
    public static void resume() {
        if (mPlayer != null && isPause) {
            mPlayer.start();
            isPause = false;
        }
    }

    public static void release() {
        if (mPlayer != null) {
            mPlayer.release();
            mPlayer = null;
        }
    }


}
